package com.zj.juc.study.completion;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author 自己的名字
 * @version 1.0.0
 * @ClassName CompletableFutureDemo
 * @Description CompletableFuture
 * @createTime 2024年12月21日 14:59
 */
public class CompletableFutureDemo {
    public static void main(String[] args) throws Exception {
        //核心的四大静态方法
        //new 方法调用是不合规地
        //runAsync 不带线程池
//        asyncNoExecutor();
        //runAsync带线程池
//        asyncWithExecutor();
        //supplyAsync 不带线程池
        supplyAsyncWithNoExecutor();

    }

    private static void asyncNoExecutor() throws Exception{
        CompletableFuture<Void> async = CompletableFuture.runAsync(() -> {
            System.out.println(Thread.currentThread().getName());
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        //使用默认的ForkJoinPool线程池
        System.out.println(async.get());
    }

    private static void asyncWithExecutor() throws Exception{
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        CompletableFuture<Void> async = CompletableFuture.runAsync(() -> {
            System.out.println(Thread.currentThread().getName());
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },executorService);
        //使用给定的线程池
        System.out.println(async.get());
        executorService.shutdown();
    }

    private static void supplyAsyncWithNoExecutor() throws Exception{
        CompletableFuture<String> async = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName());
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "executor has bean finished";
        });
        //使用自带的ForkJoinPool线程池
        System.out.println(async.get());
    }
}
